import * as path from "path";
import { Module } from "@nestjs/common";
import { RouterModule } from "nest-router";
import { MobileClientModule } from "./mobile-client/mobile-client.module";
import { ConfigModule } from "./config/config.module";
import { Oauth2Module } from "./oauth2/oauth2.module";
import { I18nModule, I18nJsonParser, I18nResolver, QueryResolver, CookieResolver } from "nestjs-i18n";
import { LinkModule } from "./link/link.module";
import { VersionModule } from "./api/version.module";
import { parse } from "accept-language-parser";
import { routes } from "./routes";
import { LoggerModule } from "./logger/logger.module";
import { SsoModule } from "./sso/sso.module";

class AcceptLanguageResolver implements I18nResolver {
    async resolve(context) {
        const req = context.switchToHttp().getRequest();
        const lang = req.raw ? req.raw.headers["accept-language"] : req.headers["accept-language"];
        if (lang) {
            let [{ code, script, region }] = parse(lang);
            code = code?.toLowerCase();
            script = script?.toLowerCase();
            region = region?.toLowerCase();

            if (code === "zh") {
                if (script === "hans") {
                    return "zh";
                } else if (script === "hant" || region === "tw" || region === "hk") {
                    return "zh-tw";
                } else {
                    return "zh";
                }
            }
        }
        return "en";
    }
}

@Module({
    imports: [
        I18nModule.forRoot({
            fallbackLanguage: "en",
            fallbacks: {
                "en-*": "en",
                "zh-hk": "zh-tw",
                "zh-tw": "zh-tw",
                "zh-*": "zh",
            },
            parser: I18nJsonParser,
            parserOptions: {
                path: path.join(__dirname, "i18n"),
            },
            resolvers: [new QueryResolver(["lang"]), new CookieResolver(["lang"]), AcceptLanguageResolver],
        }),
        RouterModule.forRoutes(routes),
        ConfigModule,
        MobileClientModule,
        Oauth2Module,
        LinkModule,
        LoggerModule,
        SsoModule,
        VersionModule,
    ],
})
export class AppModule {}
